// 自动刷新考试状态
function refreshExamStatus() {
    fetch('/exam/check_exam_status/', {
        method: 'GET',
        headers: {
            'X-Requested-With': 'XMLHttpRequest'
        }
    })
    .then(response => response.json())
    .then(data => {
        // 更新每个考试的状态
        data.exams.forEach(exam => {
            const examContainer = document.querySelector(`[data-exam-id="${exam.id}"]`);
            if (examContainer) {
                const statusElement = examContainer.querySelector('.exam-status');
                const actionElement = examContainer.querySelector('.exam-action');

                if (statusElement) {
                    statusElement.textContent = exam.status_display;
                }

                if (actionElement) {
                    if (exam.status === 'in_progress' && exam.is_registered && !exam.is_started) {
                        // 显示进入考场按钮
                        actionElement.innerHTML = `
                            <a href="/exam/enter_exam/${exam.id}/" class="btn btn-success">
                                进入考场
                            </a>`;
                    } else if (exam.status === 'preparing' && exam.is_registered) {
                        // 显示倒计时
                        const startTime = new Date(exam.start_time).getTime();
                        const now = new Date().getTime();
                        const timeLeft = Math.max(0, Math.floor((startTime - now) / 1000));

                        actionElement.innerHTML = `
                            <button class="btn btn-secondary" disabled>
                                距离开考还有 ${Math.floor(timeLeft/60)}分${timeLeft%60}秒
                            </button>`;
                    }
                }
            }
        });
    })
    .catch(error => console.error('Error:', error));
}

// 每5秒刷新一次状态
setInterval(refreshExamStatus, 5000);

// 页面加载完成后立即执行一次
document.addEventListener('DOMContentLoaded', refreshExamStatus);